<template>
  <div class="p-6px">
    <el-card class="rounded-md" shadow="never">
      <!-- 搜索条件 -->
      <el-form v-show="showSearch" :inline="true" id="searchFormId" @submit.prevent>
        <el-row>
          <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
            <el-form-item label="订单状态" prop="status">
              <el-radio-group v-model="searchParams.status" size="small" @change="handleListPage">
                <div v-for="(item, _index) in orderTextMap.status" :key="_index">
                  <el-badge :value="statusBadgeMap[item.value]">
                    <el-radio-button :label="item.value">
                      {{ item.label }}
                    </el-radio-button>
                  </el-badge>
                </div>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="订单号" prop="username">
          <el-input placeholder="请输入订单号" v-model="searchParams.order_no" clearable style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item label="退款时间" prop="username">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            value-format="YYYY-MM-DD"
            start-placeholder="开始日期"
            range-separator="至"
            end-placeholder="结束日期"
            :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="search" plain v-debounce="handleSearch">搜索</el-button>
          <el-button type="danger" icon="refresh" plain v-throttle="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 表格头部按钮 -->
      <el-row :gutter="10">
        <!-- <el-col :span="1.5" v-auth="['system:role:add']">
        </el-col> -->
        <KoiToolbar v-model:showSearch="showSearch" @refresh-table="handleListPage"></KoiToolbar>
      </el-row>

      <br />
      <el-table v-loading="loading" v-adaptive border :data="tableList" empty-text="暂时没有数据哟">
        <el-table-column label="订单号" prop="order_no" fixed="left" width="180px" align="center" :show-overflow-tooltip="true">
          <template #default="scope">
            <div>{{ scope.row.order_no }}</div>
          </template>
        </el-table-column>
        <el-table-column label="退款商品" prop="order_no" width="400px" align="center">
          <template #default="scope">
            <div>
              <div v-for="(item, index) in scope.row.detail" :key="index" style="display: flex">
                <div>
                  <el-image
                    style="width: 84px; height: 84px"
                    :preview-teleported="true"
                    :preview-src-list="item.logo"
                    :src="item.logo"
                  >
                    <template #error>
                      <el-icon class="c-[--el-color-primary]" :size="36">
                        <CircleCloseFilled />
                      </el-icon>
                    </template>
                  </el-image>
                </div>
                <div>
                  <el-tooltip class="box-item" effect="dark" :content="item.goods_name" placement="top">
                    <div style="width: 300px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis">
                      {{ item.goods_name }}
                    </div>
                  </el-tooltip>

                  <div>{{ item.sku_name }}</div>
                  <div style="color: #f56c6c">￥{{ item.price }} x {{ item.num }}</div>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="退款人" prop="order_no" width="120px" align="center" :show-overflow-tooltip="true">
          <template #default="scope">
            <div>{{ scope.row.user_name }}</div>
            <div>ID:{{ scope.row.user_id }}</div>
          </template>
        </el-table-column>
        <el-table-column label="退款图片" prop="avatar" width="100px" align="center">
          <template #default="scope">
            <div class="flex justify-center">
              <el-image
                class="w-72px h-72px"
                :preview-teleported="true"
                :preview-src-list="scope.row.refund_img"
                :src="scope.row.refund_img[0] != null && scope.row.refund_img[0] !== '' ? scope.row.refund_img[0] : ''"
              >
                <template #error>
                  <el-icon class="c-[--el-color-primary]" :size="36">
                    <CircleCloseFilled />
                  </el-icon>
                </template>
              </el-image>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="申请金额" prop="refund_price" align="center" width="100px" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="实退金额" prop="refunded_price" align="center" width="100px" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column
          label="退款时间"
          prop="create_time"
          align="center"
          width="180px"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          label="退款状态"
          prop="status_text"
          align="center"
          width="100px"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          label="退款原因"
          prop="apply_refund_reason"
          width="250px"
          align="center"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column label="详细原因" prop="remark" align="center"  width="250px" :show-overflow-tooltip="true"></el-table-column>

        <el-table-column label="拒绝原因" prop="unrefund_reason" align="center"
        width="250px"
         :show-overflow-tooltip="true"></el-table-column>
        <el-table-column
          label="操作"
          align="left"
          width="350"
          fixed="right"
          v-auth="['system:role:update', 'system:role:delete']"
        >
          <template #default="{ row }">
            <div v-if="row.status == 1">
              <el-button type="primary" size="small" plain @click="handleUpdate(row, 'agree')" v-auth="['system:role:update']">
                同意
              </el-button>
              <el-button type="danger" size="small" plain @click="handleUpdate(row, 'refuse')" v-auth="['system:role:update']">
                拒绝
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <br />
      <!-- 分页 -->
      <el-pagination
        background
        v-model:current-page="searchParams.pageNo"
        v-model:page-size="searchParams.pageSize"
        v-show="total > 0"
        :page-sizes="[10, 20, 50, 100, 200]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleListPage"
        @current-change="handleListPage"
      />

      <KoiDialog
        ref="koiDialogRef"
        :title="title"
        height="200"
        @koiConfirm="handleConfirm"
        @koiCancel="handleCancel"
        :loading="loading"
      >
        <template #content>
          <el-form ref="formRef" :rules="rules" :model="form" label-width="150px" status-icon>
            <el-row>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="订单号" prop="username">
                  <el-input v-model="form.order_no" disabled clearable />
                </el-form-item>
                <el-form-item label="申请退款金额" prop="refund_price">
                  <el-input v-model="form.refund_price" disabled clearable />
                </el-form-item>
                <el-form-item label="实际退款金额" prop="refunded_price" v-if="title == '同意'">
                  <el-input v-model="form.refunded_price" placeholder="请输入实际退款金额" clearable />
                </el-form-item>

                <el-form-item label="不同意退款的原因" prop="unrefund_reason" v-if="title == '拒绝'">
                  <el-input
                    type="textarea"
                    :rows="3"
                    v-model="form.unrefund_reason"
                    placeholder="请输入不同意退款的原因"
                    clearable
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </KoiDialog>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="refundPage">
import { agree, getStatusMap, listPage, refuse } from "@/api/order/refund/index.ts";
import { koiDatePicker } from "@/utils/index.ts";
import { koiMsgError, koiNoticeError } from "@/utils/koi.ts";
import { onMounted, reactive, ref } from "vue";

// 数据表格加载页面动画
const loading = ref(false);
/** 是否显示搜索表单 */
const showSearch = ref<boolean>(true); // 默认显示搜索条件
// 数据表格数据
const tableList = ref<any>([]);
const statusBadgeMap = ref<any>({});
// 查询参数
const searchParams = ref({
  pageNo: 1, // 第几页
  pageSize: 10, // 每页显示多少条
  order_no: "",
  status: ""
});

const total = ref<number>(0);

// 重置搜索参数
const resetSearchParams = () => {
  searchParams.value = {
    pageNo: 1,
    pageSize: 10,
    order_no: "",
    status: ""
  };
};

/** 搜索 */
const handleSearch = () => {
  searchParams.value.pageNo = 1;
  handleListPage();
};

/** 重置 */
const resetSearch = () => {
  resetSearchParams();
  handleListPage();
};

// 时间
const dateRange = ref();
/** @current-change：点击分页组件页码发生变化：例如：切换第2、3页 OR 上一页 AND 下一页 OR 跳转某一页 */
/** @size-change：点击分页组件下拉选中条数发生变化：例如：选择10条/页、20条/页等 */
// 分页查询，@current-change AND @size-change都会触发分页，调用后端分页接口
/** 数据表格 */
const handleListPage = async () => {
  try {
    loading.value = true;
    tableList.value = []; // 重置表格数据
    const res: any = await listPage(koiDatePicker(searchParams.value, dateRange.value, "created"));
    tableList.value = res.data.records;
    total.value = res.data.total;
    statusBadgeMap.value = res.data.status_badge;
    loading.value = false;
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试");
  }
};
const orderTextMap = ref<any>({});
onMounted(() => {
  // 获取数据表格数据
  handleOrderTextMap();
  handleListPage();
});
const handleOrderTextMap = async () => {
  getStatusMap().then((r: any) => (orderTextMap.value = r.data));
};

/** 修改 */
const handleUpdate = async (row: any, action: any) => {
  // 重置表单
  resetForm();
  // 标题
  title.value = action === "agree" ? "同意" : "拒绝";
  const id = row.id;
  if (id == null || id == "") {
    koiMsgError("请选中需要修改的数据");
  }
  form.value.id = row.id;
  form.value.order_no = row.order_no;
  form.value.refund_price = row.refund_price;
  form.value.refunded_price = row.refund_price;
  // handleEcho(id);
  koiDialogRef.value.koiOpen();
};

const koiDialogRef = ref();
// 标题
const title = ref("同意");
// form表单Ref
const formRef = ref<any>();

// form表单
let form = ref<any>({
  id: 0,
  refund_price: 0, //申请退款
  refunded_price: 0, //实际退款
  order_no: "",
  unrefund_reason: ""
});

/** 清空表单数据 */
const resetForm = () => {
  form.value = {
    id: 0,
    refund_price: 0,
    refunded_price: 0,
    order_no: "",
    unrefund_reason: ""
  };
};

/** 表单规则 */
const rules = reactive({});

// 确定按钮是否显示loading
const confirmLoading = ref(false);
/** 确定  */
const handleConfirm = () => {
  if (!formRef.value) return;
  confirmLoading.value = true;
  (formRef.value as any).validate(async (valid: any) => {
    if (valid) {
      try {
        if (title.value == "同意") {
          await agree(form.value);
        } else {
          await refuse(form.value);
        }
        resetForm();
        handleListPage();
        koiDialogRef.value.koiQuickClose();
      } catch (error) {
        console.log(error);
        confirmLoading.value = false;
        koiNoticeError("操作失败，请刷新重试");
      } finally {
        confirmLoading.value = false;
      }
    } else {
      koiMsgError("验证失败，请检查填写内容");
      confirmLoading.value = false;
    }
  });
};

/** 取消 */
const handleCancel = () => {
  koiDialogRef.value.koiClose();
};
</script>

<style lang="scss" scoped></style>
